<?php defined('SYSPATH') or die('No direct script access.');
include BASEPATH.'/supplier/application/classes/model/supplier.php';
/**
 * Created by PhpStorm.
 * Author: daisc
 * QQ: 2444329889
 * Time: 2018/01/12 14:05
 * Desc: desc
 */

class  Controller_Pc_Brokerage extends Stourweb_Controller
{
    private $_id;
    private $_user_info;

    function before()
    {
        parent::before();

        //登录状态判断
        $this->_id = Cookie::get('st_supplier_id');
        if (empty($this->_id)) {
            $this->request->redirect('pc/login');
        } else {
            $this->_user_info = Model_Supplier::get_supplier_byid($this->_id);
            $this->assign('userinfo', $this->_user_info);
        }
    }


    //首页
    public function action_index()
    {
        $pagesize = 10;
        $page = $_GET['page'] ? $_GET['page'] : 1;
        $status = intval($_GET['status']);
        $type = intval($_GET['type']);
        $keyword = Arr::get($_GET,'keyword');
        $stattime = Arr::get($_GET,'stattime');
        $endtime = Arr::get($_GET,'endtime');
        $channel_id = Arr::get($_GET,'channel_id');
        $channel_id = $channel_id?$channel_id:1;

        $where = "a.id>0 and a.supplierlist={$this->_id} ";
        if ($status) {
            $where .= "and a.status={$status} ";
        }
        if ($keyword) {
            $where .= "and (b.productname like '%{$keyword}%' or a.ordersn like '%{$keyword}%') ";
        }

        if(!empty($type) && $type != 0)
        {
            $where .= "and b.typeid={$type} ";
        }

        if(!empty($stattime))
        {
            $time = strtotime($stattime);
            $where .= "and a.addtime>={$time} ";
        }

        if(!empty($endtime))
        {
            $time = strtotime($endtime);
            $where .= "and a.addtime<={$time} ";
        }

        if($channel_id){
            $where .= "AND b.channel_id={$channel_id} ";
        }
        $start = ($page - 1) * $pagesize;

        $query_field = 'a.*,b.productname,b.status AS order_status,c.suppliername,b.paytype,b.dingjin';
        $sql = "SELECT *query* FROM sline_supplier_brokerage AS a ";
        $sql.= "LEFT JOIN sline_member_order AS b ON(a.ordersn=b.ordersn) ";
        $sql.= "LEFT JOIN sline_supplier AS c ON(a.supplierlist=c.id) ";
        $sql.= "WHERE {$where} ";
        $total_sql = $sql;
        $sql.= "ORDER BY a.addtime DESC ";
        $sql.= "LIMIT {$start},{$pagesize}";

        $total = DB::query(1, str_replace('*query*','count(*) AS num',$total_sql))->execute()->get('num');
        $list = DB::query(1, str_replace('*query*',$query_field,$sql))->execute()->as_array();

        foreach ($list as &$l) {
            $l['addtime'] = date('Y-m-d H:i:s', $l['addtime']);
            $l['open_price'] = $l['brokerage'] - $l['finish_brokerage'];
            if($l['order_status']==4)
            {
                $l['open_price'] = 0;
            }
        }
        unset($l);
        $route_array = array(
            'controller' => $this->request->controller(),
            'action' => $this->request->action(),
        );
        $pager = Pagination::factory(
            array(
                'current_page' => array('source' => 'query_string', 'key' => 'page'),
                'view' => 'default/pagination/brokerage',
                'total_items' => $total,
                'items_per_page' => $pagesize,
                'first_page_in_url' => false,
            )
        );
        //配置访问地址 当前控制器方法
        $pager->route_params($route_array);

        $apply_product = array();
        $product_list = Model_Supplier::get_authorization_product_list();
        $authorization_list = explode(",", $this->_user_info["authorization"]);
        foreach ($product_list as $product)
        {
            if (in_array($product["id"], $authorization_list))
            {
                $apply_product[] = $product;
            }
        }
        $channel = Model_Supplier::get_ota_channel($this->_id,true);
        foreach ($channel as &$v){
            $v['selected'] = $v['id']==$channel_id?1:0;
        }

        $this->assign('channel',$channel);
        $this->assign('apply_product',$apply_product);
        $this->assign('pageinfo', $pager);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->assign('type', $type);
        $this->assign('stattime', $stattime);
        $this->assign('endtime', $endtime);
        $this->assign('keyword', $keyword);
        $this->display('pc/brokerage/index');
    }

    //提现记录
    public function action_approval()
    {

        $pagesize = 20;
        $page = $_GET['page'] ? $_GET['page'] : 1;
        $status = $_GET['status'];
        $where = " a.id>0 and b.id>0 and a.supplierid=" . $this->_id;
        switch ($status) {
            case 1://未审核
                $where .= " and a.status=0";
                break;
            case 2://审核未通过
                $where .= " and a.status=2";
                break;
            case 3:
                $where .= " and a.status=1";
                break;
        }
        $start = ($page - 1) * $pagesize;
        $total_sql = "select COUNT(*) as num from sline_supplier_finance_drawcash as a LEFT JOIN sline_supplier as b on a.supplierid=b.id WHERE $where ";
        $total = DB::query(1, $total_sql)->execute()->get('num');

        $sql = "select a.*,b.suppliername from sline_supplier_finance_drawcash as a LEFT JOIN sline_supplier as b on a.supplierid=b.id WHERE $where ORDER by a.id desc limit $start,$pagesize";
        $list = DB::query(1, $sql)->execute()->as_array();
        foreach ($list as &$l) {
            $l['addtime'] = date('Y-m-d H:i:s', $l['addtime']);
            $l['proceeds_type_title'] = Model_Supplier_Brokerage::get_proceeds_type($l['proceeds_type']);
            $l = array_merge($l, Model_Supplier_Brokerage::get_supplier_price_info($l['supplierid']));
        }
        unset($l);

        $route_array = array(
            'controller' => $this->request->controller(),
            'action' => $this->request->action(),
        );
        $pager = Pagination::factory(
            array(
                'current_page' => array('source' => 'query_string', 'key' => 'page'),
                'view' => 'default/pagination/brokerage',
                'total_items' => $total,
                'items_per_page' => $pagesize,
                'first_page_in_url' => false,
            )
        );
        // 配置访问地址 当前控制器方法
        $pager->route_params($route_array);
        $price_arr = Model_Supplier_Brokerage::get_supplier_price_info($this->_id);
        $this->assign('price_arr', $price_arr); // 可提现金额¥{$price_arr['allow_price']}
        // 提现信息
        $info = DB::select()->from('supplier_finance_account')->where('supplierid','=',$this->_id)->execute()->current();
        $this->assign('info',$info);

        $this->assign('pageinfo', $pager);
        $this->assign('list', $list);
        $this->assign('status', $status);

        $this->display('pc/brokerage/approval');

    }

    //提现详情
    public function action_approval_show()
    {
        $id = intval($this->params['id']);
        $sql = "select a.*,b.suppliername  from sline_supplier_finance_drawcash as a LEFT JOIN sline_supplier as b on a.supplierid=b.id WHERE a.id=$id";
        $info = DB::query(1, $sql)->execute()->current();
        if ($info) {
            $info = array_merge($info, Model_Supplier_Brokerage::get_supplier_price_info($info['supplierid']));
            $info['proceeds_type_title'] = Model_Supplier_Brokerage::get_proceeds_type($info['proceeds_type']);
        }
        $this->assign('info', $info);


        $this->display('pc/brokerage/approval_show');
    }

    //申请提现
    public function action_approval_apply()
    {
        $info = DB::select()->from('supplier_finance_account')->where('supplierid','=',$this->_id)->execute()->current();
        $this->assign('info',$info);
        $this->display('pc/brokerage/approval_apply');
    }

    //保存提现账号
    public function action_ajax_save_approval_account()
    {
        $id = intval($_POST['id']);
        $bankcardnumber = Common::remove_xss($_POST['bankcardnumber']);
        $bankaccountname = Common::remove_xss($_POST['bankaccountname']);
        $bankname = Common::remove_xss($_POST['bankname']);
        $alipayaccount = Common::remove_xss($_POST['alipayaccount']);
        $wechataccount = Common::remove_xss($_POST['wechataccount']);
        $description = Common::remove_xss($_POST['description']);
        $proceeds_type = intval($_POST['proceeds_type']);
        $data = array(
            'supplierid'=>$this->_id,
            'proceeds_type'=>$proceeds_type,
            'bankname'=>$bankname,
            'bankcardnumber'=>$bankcardnumber,
            'bankaccountname'=>$bankaccountname,
            'alipayaccount'=>$alipayaccount,
            'description'=>$description,
            'wechataccount'=>$wechataccount,
        );
        if(empty($id))
        {
            $rsn = DB::insert('supplier_finance_account',array_keys($data))->values(array_values($data))->execute();
        }
        else
        {
            $rsn = DB::update('supplier_finance_account')->set($data)->where('id','=',$id)->execute();
        }

        if($rsn)
        {
            exit(json_encode(array('status'=>1)));
        }
        exit(json_encode(array('status'=>0)));
    }
    //保存提现申请
    public function action_ajax_save_approval()
    {
        $withdrawamount = Common::remove_xss($_POST['withdrawamount']);
        $bankcardnumber = Common::remove_xss($_POST['bankcardnumber']);
        $bankaccountname = Common::remove_xss($_POST['bankaccountname']);
        $bankname = Common::remove_xss($_POST['bankname']);
        $alipayaccount = Common::remove_xss($_POST['alipayaccount']);
        $wechataccount = Common::remove_xss($_POST['wechataccount']);
        $description = Common::remove_xss($_POST['description']);
        $proceeds_type = intval($_POST['proceeds_type']);
        $data = array(
            'supplierid'=>$this->_id,
            'withdrawamount'=>$withdrawamount,
            'proceeds_type'=>$proceeds_type,
            'bankname'=>$bankname,
            'bankcardnumber'=>$bankcardnumber,
            'bankaccountname'=>$bankaccountname,
            'alipayaccount'=>$alipayaccount,
            'description'=>$description,
            'wechataccount'=>$wechataccount,
            'addtime'=>time(),

        );
        $rsn = DB::insert('supplier_finance_drawcash',array_keys($data))
            ->values(array_values($data))->execute();
        if($rsn)
        {
            exit(json_encode(array('status'=>1)));
        }
        exit(json_encode(array('status'=>0)));
    }



    //统计
    public function action_stat()
    {
        $price_arr = Model_Supplier_Brokerage::get_supplier_price_info($this->_id);
        //总结算金额
        $total_brokerage_price =  DB::query(Database::SELECT,"select sum(a.brokerage) as total from sline_supplier_brokerage a left join sline_member_order b on a.ordersn=b.ordersn where a.supplierlist='".$this->_id."' and b.status in(2,5) ")->execute()->get('total');


        //未结算金额
        $wait_brokerage_price = $total_brokerage_price - $price_arr['brokerage_price'];

        $price_arr['total_brokerage_price'] = $total_brokerage_price;
        $price_arr['wait_brokerage_price'] = $wait_brokerage_price;

        $this->assign('price_arr', $price_arr);
        $this->display('pc/brokerage/stat');
    }

    public function action_ajax_smscode_validate()
    {
        if(!$this->request->is_ajax())
        {
            echo json_encode(array('status' => 0,'msg' => '请求异常'));
            exit;
        }
        $smscode = Common::remove_xss(Arr::get($_POST,'smscode'));
        if (Common::session('msg_code') != $smscode)
        {
            echo json_encode(array('status' => 0,'msg' => '“短信验证码”错误'));
        }
        else
        {
            echo json_encode(array('status' => 1, 'msg' => '验证码验证成功'));
            Common::session('msg_code', null);
        }
    }

    /**
     * 导出 excel
     */
    public function action_ajax_excel()
    {
        $status = $_GET['status'];
        $where = " a.id>0 and b.id>0 and a.supplierid=" . $this->_id;
        switch ($status) {
            case 1://未审核
                $where .= " and a.status=0";
                break;
            case 2://审核未通过
                $where .= " and a.status=2";
                break;
            case 3:
                $where .= " and a.status=1";
                break;
        }

        $total_sql = "select COUNT(*) as num from sline_supplier_finance_drawcash as a LEFT JOIN sline_supplier as b on a.supplierid=b.id WHERE $where ";
        $total = DB::query(1, $total_sql)->execute()->get('num');

        $sql = "select a.*,b.suppliername from sline_supplier_finance_drawcash as a LEFT JOIN sline_supplier as b on a.supplierid=b.id WHERE $where ORDER by a.id desc";
        $list = DB::query(1, $sql)->execute()->as_array();
        foreach ($list as &$v)
        {
            $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
            $v['proceeds_type_title'] = Model_Supplier_Brokerage::get_proceeds_type($v['proceeds_type']);
            if($v['status']==0){
                $v['status_name'] = '待审核';
            }
            elseif ($v['status']==1)
            {
                $v['status_name'] = '已提现';
            }
            else
            {
                $v['status_name'] = '未通过';
            }
        }
        $excel = $this->gene_excel($list);
        $filename = date('Ymdhis');
        ob_end_clean();//清除缓冲区
        header('Pragma:public');
        header('Expires:0');
        header('Content-Type:charset=utf-8');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header('Content-Disposition:attachment;filename=' . $filename . ".xls");
        header('Content-Transfer-Encoding:binary');
        echo iconv('utf-8', 'gbk', $excel);
        exit();
    }

    protected function gene_excel($order_list)
    {

        $table = "<table border='1' ><tr>";
        $table .= "<td>银行卡号</td>";
        $table .= "<td>账户名</td>";
        $table .= "<td>开户银行</td>";
        $table .= "<td>支付宝账号</td>";
        $table .= "<td>微信账号</td>";
        $table .= "<td>备注说明</td>";
        $table .= "<td>提现时间</td>";
        $table .= "<td>提现金额</td>";
        $table .= "<td>提现状态</td>";
        $table .= "<td>提现渠道</td>";
        $table .= "<td>供应商</td>";
        $table .= "</tr>";
        foreach ($order_list as $row)
        {

            $table .= "<tr>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['bankcardnumber']}</td>";
            $table .= "<td>{$row['bankaccountname']}</td>";
            $table .= "<td>{$row['bankname']}</td>";
            $table .= "<td>{$row['alipayaccount']}</td>";
            $table .= "<td>{$row['wechataccount']}</td>";
            $table .= "<td>{$row['description']}</td>";
            $table .= "<td>{$row['addtime']}</td>";
            $table .= "<td>{$row['withdrawamount']}</td>";
            $table .= "<td>{$row['status_name']}</td>";
            $table .= "<td>{$row['proceeds_type_title']}</td>";
            $table .= "<td>{$row['suppliername']}</td>";
            $table .= "</tr>";
        }

        $table .= "</table>";
        return $table;
    }

    public function action_ajax_excel_brokerage()
    {
        $status = intval($_GET['status']);
        $type = intval($_GET['type']);
        $keyword = Common::remove_xss($_GET['keyword']);
        $stattime = Common::remove_xss($_GET['stattime']);
        $endtime = Common::remove_xss($_GET['endtime']);

        $where = "a.id>0 and a.supplierlist=" . $this->_id;
        if ($status) {
            $where .= " and a.status=$status";
        }
        if ($keyword) {
            $where .= " and (b.productname like '%$keyword%' or a.ordersn like '%$keyword%')";
        }

        if(!empty($type) && $type != 0)
        {
            $where .= " and b.typeid = {$type}";
        }

        if(!empty($stattime))
        {
            $time = strtotime($stattime);
            $where .= " and a.addtime >= {$time}";
        }

        if(!empty($endtime))
        {
            $time = strtotime($endtime);
            $where .= " and a.addtime <= {$time}";
        }


        $sql = "select a.*,b.productname,b.status as order_status,c.suppliername,b.paytype,b.dingjin from sline_supplier_brokerage as a LEFT JOIN sline_member_order as b  on a.ordersn=b.ordersn  LEFT JOIN sline_supplier as c  on  a.supplierlist=c.id WHERE $where order by a.addtime desc";
        $list = DB::query(1, $sql)->execute()->as_array();

        $excel = $this->brokerage_excel($list);
        $filename = date('Ymdhis');
        ob_end_clean();//清除缓冲区
        header('Pragma:public');
        header('Expires:0');
        header('Content-Type:charset=utf-8');
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Content-Type:application/force-download');
        header('Content-Type:application/vnd.ms-excel');
        header('Content-Type:application/octet-stream');
        header('Content-Type:application/download');
        header('Content-Disposition:attachment;filename=' . $filename . ".xls");
        header('Content-Transfer-Encoding:binary');
        echo iconv('utf-8', 'gbk', $excel);
        exit();
    }

    public function brokerage_excel($order_list )
    {
        $table = "<table border='1' ><tr>";
        $table .= "<td>订单号</td>";
        $table .= "<td>产品名称</td>";
        $table .= "<td>收款时间</td>";
        $table .= "<td>订单状态</td>";
        $table .= "<td>应结金额</td>";
        $table .= "<td>未结金额</td>";
        $table .= "<td>已结金额</td>";
        $table .= "<td>结算状态</td>";
        $table .= "</tr>";
        foreach ($order_list as $row)
        {
            $table .= "<tr>";
            $table .= "<td style='vnd.ms-excel.numberformat:@'>{$row['ordersn']}</td>";
            $table .= "<td>{$row['productname']}</td>";
            $table .= "<td>{$row['addtime']}</td>";
            if($row['order_status']==2 ){
                $table .= "<td>待消费</td>";
            }
            elseif($row['order_status']==4){
                $table .= "<td>已退款</td>";
            }
            else{
                $table .= "<td>已完成</td>";
            }
            $table .= "<td>{$row['brokerage']}</td>";
            $table .= "<td>{$row['open_price']}</td>";
            $table .= "<td>{$row['finish_brokerage']}</td>";
            if($row['status'] == 1){
                $table .= "<td>未结算</td>";
            }else{
                $table .= "<td>已结算</td>";
            }
            $table .= "</tr>";
        }

        $table .= "</table>";
        return $table;
    }

    /**
     * 各渠道结算统计
     */
    public function action_settlement_statistics()
    {
        $channel = Model_Supplier_Brokerage::get_channel_commission($this->_id);

        $this->assign('channel',$channel);
        $this->display('pc/brokerage/settlement_statistics');
    }

}